/***************************************************************************
    begin                : aug 01 2010
    copyright            : (C) 2010 by Benoit Valot
    email                : benvalot@gmail.com
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 23 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

package val.lemonde;

import java.util.ArrayList;

import val.lemonde.FragmentListArticle.OnArticleSelectedListener;
import val.lemonde.FragmentMain.OnCategorieSelectedListener;

import com.markupartist.android.widget.ActionBar;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;

public class ActivityListeArticles extends ActivityLemondeBase implements
		OnArticleSelectedListener, OnCategorieSelectedListener {
	private Categorie cat;

	private int position;

	protected ArrayList<Article> articles;

	private get_rss_url asyntask;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.d("lemonde","ActivityListeArticles onCreate");
		setContentView(R.layout.main);

		// On verifie si il n'y a pas la liste d'article
		if (savedInstanceState != null) {
			Log.d("lemonde", "On_create_liste_article_activity_from_old");
			cat = savedInstanceState.getParcelable("cat");
			position = savedInstanceState.getInt("position");
		} else {
			cat = this.getIntent().getExtras().getParcelable("cat");
			position = this.getIntent().getExtras().getInt("position");
			this.load_content();
		}
		//dual-mode
		this.loadCategorie();
		
		ActionBar actionBar = (ActionBar) findViewById(R.id.actionbar);
		actionBar.setTitle(cat.getName());
		getMenuInflater().inflate(R.menu.liste_article_menu_top,
				actionBar.asMenu());
		actionBar.setDisplayShowHomeEnabled(true);
		actionBar.setHomeLogo(R.drawable.icon);
		actionBar.setDisplayHomeAsUpEnabled(true);

	}

	public void load_data() {
		FragmentManager fragmentManager = getSupportFragmentManager();
		FragmentTransaction fragmentTransaction = fragmentManager
				.beginTransaction();
		FragmentListArticle fragment = FragmentListArticle
				.newInstance(articles);
		fragmentTransaction.replace(R.id.container, fragment, "articles");
		fragmentTransaction.commitAllowingStateLoss();
	}

	public void load_content() {
		//On arrete l'ancien 
		if (asyntask != null && !asyntask.getStatus().equals(Status.FINISHED)) {
			asyntask.cancel(true);
		}
		
		FragmentManager fragmentManager = getSupportFragmentManager();
		FragmentTransaction fragmentTransaction = fragmentManager
				.beginTransaction();
		FragmentLoad fragment = new FragmentLoad();
		fragmentTransaction.replace(R.id.container, fragment);
		fragmentTransaction.commit();
		// recuperation de l'url des flux rss
		// String url = this.getIntent().getExtras().getString("url");
		asyntask = new get_rss_url();
		asyntask.execute(cat.getUrl());
	}

	public void loadCategorie() {
		if (!this.isDualMode()) {
			return;
		}
		FragmentManager fragmentManager = getSupportFragmentManager();
		FragmentMain fragment = (FragmentMain) fragmentManager
				.findFragmentByTag("categories");
		if (fragment == null) {
			FragmentTransaction fragmentTransaction = fragmentManager
					.beginTransaction();
			fragment = new FragmentMain();
			fragmentTransaction.add(R.id.container_little, fragment,
					"categories");
			fragmentTransaction.commit();
		}
	}

	public void onSaveInstanceState(final Bundle b) {
		Log.d("lemonde", "ActivityListeArticles onSaveInstanceState");
		if (this.articles != null) {
			b.putParcelableArrayList("liste_data", this.articles);
		}
		b.putParcelable("cat", cat);
		b.putInt("position", position);
		super.onSaveInstanceState(b);
	}

	public void onRestoreInstanceState(final Bundle b) {
		Log.d("lemonde", "ActivityListeArticles onRestoreInstanceState");
		super.onRestoreInstanceState(b);
		this.articles = b.getParcelableArrayList("liste_data");
		if (this.articles == null) {
			Log.d("lemonde", "Rien a recuperer");
			asyntask = new get_rss_url();
			asyntask.execute(cat.getUrl());
		}
	}

	@Override
	protected void onDestroy() {
		Log.d("lemonde", "ActivityListeArticles onDestroy");
		if (asyntask != null && !asyntask.getStatus().equals(Status.FINISHED)) {
			asyntask.cancel(true);
		}
		super.onDestroy();
	}

	@Override
	public void onCategorieSelected(Categorie cat, int pos) {
		this.cat = cat;
		this.position = pos;
		ActionBar actionBar = (ActionBar) findViewById(R.id.actionbar);
		actionBar.setTitle(cat.getName());
		this.load_content();
	}

	@Override
	public void OnArticleSelected(Article art, int pos) {
		Intent i = new Intent(this, ActivityPage.class);
		i.putExtra("article", art);
		i.putExtra("articles", articles);
		i.putExtra("position", pos);
		this.startActivity(i);
	}

	public void set_articles(ArrayList<Article> art) {
		this.articles = art;
	}

	private void choixMultipleLecture() {
		if (articles == null)
			return;
		// Demande si tout marquer ou demarquer ou annuler
		final CharSequence[] items = { "Comme lu", "Comme non Lu", "Annuler" };
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Marquer tout les articles");
		builder.setItems(items, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int item) {
				if (items[item].equals("Comme lu")) {
					ActivityListeArticles.this.marquerMultipleLecture(true);
				} else if (items[item].equals("Comme non Lu")) {
					ActivityListeArticles.this.marquerMultipleLecture(false);
				}
			}
		});
		AlertDialog alert = builder.create();
		alert.show();
	}

	private void marquerMultipleLecture(boolean sens) {
		for (Article art : articles) {
			if (sens)
				this.get_datas().add_articles_lues(art.getLinkUri());
			else
				this.get_datas().remove_articles_lues(art.getLinkUri());
		}
		if (articles.size() > 0)
			this.load_data();
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.layout.liste_article_menu, menu);
		return super.onCreateOptionsMenu(menu);
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.check_item:
			this.choixMultipleLecture();
			return true;
		case R.id.update_item:
			this.load_content();
			return true;
		case R.id.actionbar_item_home:
			Log.d("lemonde", "home");
			this.finish();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	private class get_rss_url extends AsyncTask<String, Void, String> {
		Boolean loadImage;
		ArrayList<Article> articles;
		ImageCache cache;

		// can use UI thread here
		protected void onPreExecute() {
			loadImage = ActivityListeArticles.this.get_datas()
					.isLoadImageEnabled();
			cache = ActivityListeArticles.this.get_datas()
					.getImageCache();
		}

		// automatically done on worker thread (separate from UI thread)
		protected String doInBackground(String... args) {
			// List<String> names =
			// Main.this.application.getDataHelper().selectAll();
			try {
				RssDownload rss = new RssDownload(args[0]);
				rss.get_rss_articles();
				articles = rss.getArticles();
				// Si image activée
				if (loadImage) {
					cache.clearMemoryCache();
					for (Article art : articles) {
						cache.addBitmapToCache(art.getMediaLink());
					}
				}
			} catch (Exception e) {
				String error = e.toString() + "\n" + e.getStackTrace()[0]
						+ "\n" + e.getStackTrace()[1];
				return (error);
			}
			return null;
		}

		protected void onPostExecute(String error) {
			if (error == null) {
				ActivityListeArticles.this.set_articles(articles);
				ActivityListeArticles.this.load_data();
			} else {
				ActivityListeArticles.this.erreur_loading(error);
			}
			// Main.this.output.setText(result);
		}
	}

}
